<?php

class Support extends Front_Controller {
	
	function __construct()
	{
 		parent::__construct();
		$this->load->library('form_validation');
		$this->load->model('support_model');
	}	
	function index()
	{			
		$this->form_validation->set_rules('email', 'Your e-mail', 'required|trim|xss_clean|valid_email|max_length[500]');			
		$this->form_validation->set_rules('nom', 'First name', 'required|trim|xss_clean|max_length[100]');			
		$this->form_validation->set_rules('prenom', 'Last name', 'trim|xss_clean|max_length[100]');			
		$this->form_validation->set_rules('societe', 'Company', 'trim|xss_clean|max_length[200]');		
		$this->form_validation->set_rules('subjet', 'Subject', 'trim|xss_clean|max_length[200]');	
		$this->form_validation->set_rules('demande', 'Message', 'required|trim|xss_clean');
			
		$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
	
		if ($this->form_validation->run() == FALSE) // validation hasn't been passed
		{
			$this->load->view('support');
		}
		else // passed validation proceed to post success logic
		{
		 	// build array for the model
			
			$form_data = array(
					       	'email' => set_value('email'),
					       	'nom' => set_value('nom'),
					       	'prenom' => set_value('prenom'),
					       	'societe' => set_value('societe'),
					       	'demande' => set_value('demande'),
					       	'subjet' => set_value('subjet'),
							'ip'=>$this->input->ip_address()
						);
					
			// run insert model to write data to db
		
			if ($this->support_model->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
			{
				redirect('support/success');   // or whatever logic needs to occur
			}
			else
			{
				//echo 'An error occurred saving your information. Please try again later';
				echo "An error occurred saving your personal information. Please try again later";
				// Or whatever error handling is necessary
			}
		}
	}
	function success()
	{
			//send email
			$message=
			$this->input->post('nom')." <br/>\n".
			$this->input->post('prenom')." <br/>\n".
			$this->input->post('societe')." <br/>\n".
			$this->input->ip_address()." <br/> <br/>\n".
			$this->input->post('message');
			
			
			$config = Array('mailtype' => 'html',
					'charset' => 'utf-8',
					'wordwrap' => TRUE );
			$this->load->library('email', $config);
			
			$this->email->from($this->input->post('email'), $this->input->post('nom'));
			$this->email->to($this->config->item('email'));
			$this->email->subject($this->input->post('subjet'));
			$this->email->message($message);
			$this->email->send();
			$data=array('message_success'=> 'Your request has been registered, We will contact you as soon as possible');

			$this->load->view('support',$data);
			
	}
}
